package com.bjfu.gmms.servlet;

import com.bjfu.gmms.MyBatisUtil;
import com.bjfu.gmms.mapper.MentorMapper;
import com.bjfu.gmms.model.Mentor;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;

@WebServlet("/upload")
public class FileUploadServlet extends HttpServlet {

    // private static final String UPLOAD_DIRECTORY = "webapp/imgs";

    private static final int MAX_FILE_SIZE = 1024 * 1024 * 10; // 10MB
    private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 检查是否为文件上传请求
        if (!ServletFileUpload.isMultipartContent(request)) {
            response.getWriter().write("请求类型错误！");
            return;
        }
        // 获取导师ID
        HttpSession session = request.getSession();
        Mentor mentor = (Mentor) session.getAttribute("mentor");
        Integer int_mentorId = mentor.getMentorId();
        String mentorId = int_mentorId.toString();

        // 设置上传文件的最大大小
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(MAX_FILE_SIZE);
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setFileSizeMax(MAX_FILE_SIZE);
        upload.setSizeMax(MAX_REQUEST_SIZE);

        try {
            // 解析请求中的所有文件项
            List<FileItem> formItems = upload.parseRequest(request);
            SqlSession sqlSession = MyBatisUtil.getSqlSession("development");
            MentorMapper mapper = sqlSession.getMapper(MentorMapper.class);
            mentor.setMentorImg(mentorId + ".jpg");
            if (formItems != null && formItems.size() > 0) {
                for (FileItem item : formItems) {
                    // 处理上传的文件
                    if (!item.isFormField()) {
                        // 保存文件到指定目录
                        String filePath = "D:\\keshe_dataset_code\\src\\main\\webapp\\imgs\\" + mentorId + ".jpg";
                        System.out.println(filePath);
                        File storeFile = new File(filePath);
                        item.write(storeFile);

                        mapper.updateMentorInfo(mentor);
                        sqlSession.commit();
                        // 在此可以将文件路径保存到数据库中
                        response.getWriter().write("upload success, filePath：" + filePath);
                    }
                }
            }
        } catch (Exception ex) {
            response.getWriter().write("文件上传失败：" + ex.getMessage());
        }
    }
}